<template>
  <div class="upload-file">
    <el-button type="primary" :disabled="disabled" @click="openUpload">选取文件</el-button>
    <!-- 文件列表 -->
    <transition-group class="upload-file-list el-upload-list el-upload-list--text" name="el-fade-in-linear" tag="ul">
      <li class="el-upload-list__item ele-upload-list__item-content" v-for="(file, index) in newFileList" :key="index">
        <el-link @click="handleDownload(file)" :underline="false" target="_blank">
          <span class="el-icon-document">&nbsp;&nbsp;{{ getFileName(file.name) }} </span>
        </el-link>
        <div class="ele-upload-list__item-content-action">
          <el-link :underline="false" @click="handleDelete(index, file)" type="danger" :disabled="disabled">删除</el-link>
        </div>
      </li>
    </transition-group>
    <!-- 上传对话框 -->
    <el-dialog v-if="upload.open" :title="upload.title" v-model="upload.open" width="400px" append-to-body
      custom-class="dialogTable">
      <p></p>
      <el-upload multiple :action="uploadFileUrl" :before-upload="handleBeforeUpload" :limit="limits"
        :on-change="handleChange" :on-error="handleUploadError" :on-remove="handleRemove" :on-exceed="handleExceed"
        :on-success="handleUploadSuccess" v-model:file-list="fileList" :show-file-list="true" :headers="upload.headers" class="upload-file-uploader"
        ref="uploads" :auto-upload="true" style="display: inline-block" :disabled="disabled" :fileType="fileType" drag>
        <el-icon class="el-icon--upload">
          <upload-filled />
        </el-icon>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <template #tip>
          <!-- 上传提示 -->
          <div class="el-upload__tip text-center">
            <template v-if="showTip && isSpatialData == '0'">
              请上传
              <template v-if="fileSize"> 大小不超过 <b style="color: #f56c6c">{{ fileSize }}MB</b> </template>
              <template v-if="fileType.length != 0"> 格式为 <b style="color: #f56c6c">{{ fileType.join(",") }}</b>
              </template>
              的文件
            </template>
            <template v-if="showTip && isSpatialData != '0'">
              导入多个文件时，文件名称需相同。支持上传多个文件。
            </template>
            <template v-if="name">
              <el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;"
                @click="importTemplate(name)" v-if="isSpatialData == '0'">下载模板</el-link>
            </template>
          </div>
        </template>
      </el-upload>
      <template #footer>
        <div class="dialog-footer">
          <!-- <el-button type="primary" :disabled="(fileList.length == 0) || (isSpatialData == '1' && uploadDisabled)" @click="submitFileForm">确 定</el-button> -->
          <el-button type="primary" @click="submitFileForm">确 定</el-button>
          <el-button @click="(upload.open = false)">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 上传图片 -->
    <el-drawer v-model="openDrawer" direction="btt" append-to-body size="40%" :close-on-click-modal="false"
      :show-close="false">
      <template #title>
        <h4>{{ title }}</h4>
        <el-button type="primary" @click="cancelDrawer">关 闭</el-button>
      </template>
      <template #default>
        <el-table v-loading="loading" ref="tableRefs" :data="dataList" stripe>
          <template v-for="item in titleList">
            <template v-if="item.fieldType == 'NORMAL'">
              <el-table-column :label="item.label" align="center" :prop="item.prop" min-width="120" show-overflow-tooltip/>
            </template>
            <template v-if="item.fieldType == 'IMG'">
              <el-table-column :label="item.label" align="center" :prop="item.prop" min-width="120" show-overflow-tooltip>
                <template #default="scope">
                  <span>{{ scope.row[`${item.prop}Pic`] }}{{ scope.row[`${item.prop}Pic`] }}</span>
                  <el-button type="text" @click="handleUplodePic(scope.row, item.prop)" v-if="!scope.row[cssStyle2DomStyle(item.prop)]||scope.row[cssStyle2DomStyle(item.prop)].length==0">上传图片</el-button>
                  <el-button type="text" @click="handleUplodePic(scope.row, item.prop)" v-if="scope.row[cssStyle2DomStyle(item.prop)]&&scope.row[cssStyle2DomStyle(item.prop)].length==1">编辑图片</el-button>
                </template>
              </el-table-column>
            </template>
            <template v-if="item.fieldType == 'REPORT'">
              <el-table-column :label="item.label" align="center" :prop="item.prop" min-width="120" show-overflow-tooltip>
                <template #default="scope">
                  <el-button type="text" @click="handleUplodeReport(scope.row, item.prop)" v-if="!scope.row[cssStyle2DomStyle(item.prop)]||scope.row[cssStyle2DomStyle(item.prop)].length==0">上传报告</el-button>
                  <el-button type="text" @click="handleUplodeReport(scope.row, item.prop)" v-if="scope.row[cssStyle2DomStyle(item.prop)]&&scope.row[cssStyle2DomStyle(item.prop)].length==1">编辑报告</el-button>
                </template>
              </el-table-column>
            </template>
            <template v-if="item.fieldType == 'SHP'">
              <el-table-column :label="item.label" align="center" :prop="item.prop" min-width="120" show-overflow-tooltip>
                <template #default="scope">
                  <el-button type="text" @click="handleUplodeShp(scope.row, item.prop)" v-if="!scope.row[cssStyle2DomStyle(item.prop)]||scope.row[cssStyle2DomStyle(item.prop)].length==0">上传空间文件</el-button>
                  <el-button type="text" @click="handleUplodeShp(scope.row, item.prop)" v-if="scope.row[cssStyle2DomStyle(item.prop)]&&scope.row[cssStyle2DomStyle(item.prop)].length==1">编辑空间文件</el-button>
                  <el-button type="text" @click="handleUplodeShp(scope.row, item.prop)" v-if="scope.row[item.prop]&&scope.row[item.prop].length>1"><el-icon><More /></el-icon></el-button>
                </template>
              </el-table-column>
            </template>
          </template>
        </el-table>
      </template>
    </el-drawer>

    <el-dialog v-model="openPic" width="500px" title="上传图片" append-to-body>
      <p class="mt15"></p>
      <div>
        <image-upload ref="imageUploadRef" :limit="5" v-model="form.reportAttach" />
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="savePic">确定</el-button>
          <el-button type="primary" @click="openPic = false">取消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 上传对话框 -->
    <el-dialog v-if="openRep" title="上传报告" v-model="openRep" width="400px" append-to-body custom-class="dialogTable">
      <p></p>
      <upload-report v-model="form.reportAttach" ref="reportRef" />
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="saveRep">确 定</el-button>
          <el-button @click="(openRep = false)">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <el-dialog v-if="openShp" title="上传空间文件" v-model="openShp" width="400px" append-to-body custom-class="dialogTable">
      <p></p>
      <uploadShp v-model="form.reportAttach" ref="shpRef"/>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="saveShp">确 定</el-button>
          <el-button @click="(openShp = false)">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { getToken } from "@/utils/auth";
import { ElMessageBox } from 'element-plus'
import { getListExcel, getListsShp, getListsTif, uploadSave, getFileData } from '@/api/essentialData/dataView'
import { upLoadFile, downLoadFile, deleteFile } from "@/api/system/attachFile";
import uploadReport from '../fileUploadReport/index.vue'
import uploadShp from '../fileUploadShp1/index.vue'

const props = defineProps({
  modelValue: [String, Object, Array],
  // 数量限制
  limit: {
    type: Number,
    default: 5,
  },
  // 大小限制(MB)
  fileSize: {
    type: Number,
    default: 1024,
  },
  // 是否是空间数据
  isSpatialData: {
    type: Number,
    default: 0,
  },
  // 文件类型, 例如['png', 'jpg', 'jpeg']
  fileType: {
    type: Array,
    //default: () => ["doc", "xls", "ppt", "txt", "pdf"],
    default: () => [],
  },
  // 是否显示提示
  isShowTip: {
    type: Boolean,
    default: true
  },
  disabled: {
    type: Boolean,
    default: false
  },
  code: {
    type: String,
    default: '',
  },
  name: {
    type: String,
    default: '',
  },
  isHasFile: {
    type: Number,
    default: 0,
  },
  ids: {
    type: Object,
    default: {},
  },
  isTif:{//是否应上传tif文件
    type: Boolean,
    default: false
  }
});

const { proxy } = getCurrentInstance();
const emit = defineEmits();
const number = ref(0);
const uploadList = ref([]);
const fileList = ref([]);
const openDrawer = ref(false);
const loading = ref(false);
const dataList = ref([]);
const titleList = ref([]);
const title = ref('');
const show = ref('0');
const showTip = computed(
  () => props.isShowTip && (props.fileType || props.fileSize)
);
const limits = computed(
  () => {
    props.isSpatialData == 0 ? 1 : 10
  }
);
const uploadFileUrl = ref(props.isSpatialData == 0?import.meta.env.VITE_APP_BASE_API + "/attachment/uploadExcelFile":import.meta.env.VITE_APP_BASE_API + "/attachment/uploadShpFile")// 上传的图片服务器地址

console.log(uploadFileUrl.value,'lallala');
const newFileList = ref([]);
const dataVersion = ref();

const openPic = ref(false);
const openRep = ref(false);
const openShp = ref(false);
const propTitle = ref('');
const uploadDisabled = ref(true);
const id = ref('');
const parseDataCacheId = ref(null);
/*** 用户导入参数 */
const upload = reactive({
  open: false,
  title: "",
  isUploading: false,
  headers: { token: "tokrn " + getToken() },
  url: props.isSpatialData == 0&& props.isSpatialData != 2?import.meta.env.VITE_APP_BASE_API + "/attachment/uploadExcelFile":import.meta.env.VITE_APP_BASE_API + "/attachment/uploadShpFile", // 上传的图片服务器地址
});

const data = reactive({
  form: {
    attach: [],
    reportAttach: [],
  },
})
const { form } = toRefs(data);
watch(()=>props.isSpatialData,val=>{
  if(val==0){
    uploadFileUrl.value = import.meta.env.VITE_APP_BASE_API + "/attachment/uploadExcelFile"
  }else{
    uploadFileUrl.value = import.meta.env.VITE_APP_BASE_API + "/attachment/uploadShpFile"
  }
})
watch(()=>props.isTif,val=>{
  if(val){
    uploadFileUrl.value = import.meta.env.VITE_APP_BASE_API + "/attachment/uploadTifFile"
  }else{
    uploadFileUrl.value = import.meta.env.VITE_APP_BASE_API + "/attachment/uploadShpFile"
  }
})
watch(() => props.modelValue, val => {
  if (val) {
    let temp = 1;
    // 首先将值转为数组
    const list = Array.isArray(val) ? val : props.modelValue.split(',');
    // 然后将数组转为对象数组
    fileList.value = list.map(item => {
      if (typeof item === "string") {
        item = { name: item, url: item };
      }
      item.attachId = item.attachId || new Date().getTime() + temp++;
      item.name = item.attachName;
      item.url = item.attachPath;
      return item;
    });
    newFileList.value = fileList.value;
  } else {
    fileList.value = [];
    newFileList.value = fileList.value;
    return [];
  }
}, { deep: true});

// 上传空间
function handleUplodeShp(row, prop) {
  form.value = {
    attach: [],
    reportAttach: [],
  };
  id.value = row.id;
  propTitle.value = prop;
  getFileData({ id: row.id, typeCode: props.code, field: prop }).then(res => {
    form.value.reportAttach = res.data ? res.data : [];
    openShp.value = true;
  })
}

// 保存空间
function saveShp() {
  const fileList = JSON.parse(JSON.stringify(proxy.$refs["shpRef"].fileList));
    const attachIds = [];
    for (var i = 0; i < fileList.length; i++) {
      attachIds.push(fileList[i].attachId)
    }
    const ids = attachIds.join(",");

  let nameArr = [];
  fileList.forEach(item => {
    const typeName = item.name.slice(item.name.lastIndexOf(".") + 1);
    nameArr.push(typeName)
  })
  if (nameArr.includes('shp' && 'dbf' && 'prj' && 'shx' && 'cpg')) {
    uploadSave({ ids: ids, id: id.value, typeCode: props.code, prop: propTitle.value }).then(res => {
      proxy.$modal.msgSuccess("保存成功");
      dataList.value = res.data;
      openShp.value = false;
    })
  } else {
    proxy.$modal.msgError(`必须上传.dbf、.prj、.shp、.shx、.cpg类型的文件！ `);
  }
}
// 上传报告
function handleUplodeReport(row, prop) {
  form.value = {
    attach: [],
    reportAttach: [],
  };
  id.value = row.id;
  propTitle.value = prop;
  getFileData({ id: row.id, typeCode: props.code, field: prop }).then(res => {
    form.value.reportAttach = res.data ? res.data : [];
    openRep.value = true;
  })
}

// 保存报告
function saveRep() {
  const fileList = JSON.parse(JSON.stringify(proxy.$refs["reportRef"].fileList));
  const attachIds = [];
  for (var i = 0; i < fileList.length; i++) {
    attachIds.push(fileList[i].attachId)
  }
  const ids = attachIds.join(",");
  uploadSave({ ids: ids, id: id.value, typeCode: props.code, prop: propTitle.value }).then(res => {
    proxy.$modal.msgSuccess("保存成功");
    dataList.value = res.data;
    openRep.value = false;
  })
}
// 字符串转驼峰
function cssStyle2DomStyle(sName) {
      var arrs = sName.split('_').filter(item => item)
      console.log(arrs);
      var name = ''

      for (const i in arrs) {
        if (i == 0) {
          name = name + arrs[0]
        } else {
          var nameArr = arrs[i].split('')
          nameArr[0] = nameArr[0].toUpperCase()
          name = name + nameArr.join('')
        }
      }
      return name
    }

// 上传图片
function handleUplodePic(row, prop) {
  form.value = {
    attach: [],
    reportAttach: [],
  };
  id.value = row.id;
  propTitle.value = prop;
  console.log(row,'id信息');
  getFileData({ id: row.id, typeCode: props.code, field: prop }).then(res => {
    form.value.reportAttach = res.data ? res.data : [];
    openPic.value = true;
  })
}

// 保存图片
function savePic() {
  const fileList = JSON.parse(JSON.stringify(proxy.$refs["imageUploadRef"].fileList));
  const attachIds = [];
  for (var i = 0; i < fileList.length; i++) {
    attachIds.push(fileList[i].attachId)
  }
  const ids = attachIds.join(",");
  loading.value = true;
  uploadSave({ ids: ids, id: id.value, typeCode: props.code, prop: propTitle.value }).then(res => {
    loading.value = false;
    proxy.$modal.msgSuccess("保存成功");
    dataList.value = res.data;
    console.log(dataList.value,'llalala');
    openPic.value = false;
  }).catch(err=>{loading.value = false;})
}

// 关闭
function cancelDrawer() {
  openDrawer.value = false;
  newFileList.value = fileList.value;
  // emit('sureUploadFile', { list: newFileList.value, tempVersionCode: dataVersion.value, fieldNum: null, fieldEntry: null });

}

// 打开图片上传
function submitFileForm() {
  if (props.isSpatialData == '1') {//空间数据
    let nameArr = [];
    fileList.value.forEach(item => {
      const typeName = item.name.slice(item.name.lastIndexOf(".") + 1);
      nameArr.push(typeName)
    })

    if (props.isTif==false && (nameArr.includes('shp' && 'dbf' && 'prj' && 'shx' && 'cpg')) && props.isSpatialData == '1') {
      newFileList.value = [];
      let id = [];
      fileList.value.forEach(item => {
        id.push(item.attachId)
      })
      proxy.$modal.loading("正在解析文件，请稍候...");
      getListsShp({ typeCode: props.code, fileIds: id.join(','), ...props.ids }).then(res => {
        proxy.$modal.closeLoading();
        console.log("getListsShp");
        console.log(res.data);
        if (res.data.code == 100001) {
          ElMessageBox.confirm(
              res.data.message,
              '消息',
              {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning',
              }
          )
              .then(() => {
                parseDataCacheId.value = res.data.cacheId;
                emit('cacheId', { parseDataCacheId: parseDataCacheId.value });

                dataList.value = res.data.list;
                titleList.value = res.data.name;
                title.value = res.data.typeName;
                dataVersion.value = res.data.dataVersion;
                show.value = res.data.show;
                if (res.data.open == '1') {
                  openDrawer.value = true;
                  newFileList.value = fileList.value;
                  emit('sureUploadFile', { list: newFileList.value, tempVersionCode: dataVersion.value, parseDataCacheId: parseDataCacheId.value, fieldNum: res.data.fieldNum, fieldEntry: res.data.fieldEntry });
                  upload.open = false;
                } else {
                  newFileList.value = fileList.value;
                  emit('sureUploadFile', { list: newFileList.value, tempVersionCode: dataVersion.value, parseDataCacheId: parseDataCacheId.value, fieldNum: res.data.fieldNum, fieldEntry: res.data.fieldEntry });
                  upload.open = false;
                }
              })
              .catch(() => {
                parseDataCacheId.value = null;
                emit('cacheId', { parseDataCacheId: parseDataCacheId.value });
                newFileList.value = [];
                emit('sureUploadFile', { list: newFileList.value, tempVersionCode: dataVersion.value, parseDataCacheId: parseDataCacheId.value, fieldNum: null, fieldEntry: null });
                upload.open = false;
              })
        } else {
          dataList.value = res.data.list;
          titleList.value = res.data.name;
          title.value = res.data.typeName;
          dataVersion.value = res.data.dataVersion;
          show.value = res.data.show;
          if (res.data.open == '1') {
            openDrawer.value = true;
            newFileList.value = fileList.value;
            emit('sureUploadFile', { list: newFileList.value, tempVersionCode: dataVersion.value, parseDataCacheId: parseDataCacheId.value, fieldNum: res.data.fieldNum, fieldEntry: res.data.fieldEntry });
            upload.open = false;
          } else {
            newFileList.value = fileList.value;
            emit('sureUploadFile', { list: newFileList.value, tempVersionCode: dataVersion.value, parseDataCacheId: parseDataCacheId.value, fieldNum: res.data.fieldNum, fieldEntry: res.data.fieldEntry });
            upload.open = false;
          }
        }

      }).catch(err => {
        proxy.$modal.closeLoading();
      });
    } else if (props.isTif && (nameArr.includes('tif')) && props.isSpatialData == '1') {
      newFileList.value = [];
      let id = [];
      fileList.value.forEach(item => {
        id.push(item.attachId)
      })
      proxy.$modal.loading("正在解析文件，请稍候...");
      getListsTif({ typeCode: props.code, fileIds: id.join(','), ...props.ids }).then(res => {
        proxy.$modal.closeLoading();
        console.log("getListsTif");
        console.log(res.data);
        if (res.data.code == 100001) {
          ElMessageBox.confirm(
            res.data.message,
            '消息',
            {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning',
            }
          )
            .then(() => {
              parseDataCacheId.value = res.data.cacheId;
              emit('cacheId', { parseDataCacheId: parseDataCacheId.value });

              dataList.value = res.data.list;
              titleList.value = res.data.name;
              title.value = res.data.typeName;
              dataVersion.value = res.data.dataVersion;
              show.value = res.data.show;
              if (res.data.open == '1') {
                openDrawer.value = true;
                newFileList.value = fileList.value;
                emit('sureUploadFile', { list: newFileList.value, tempVersionCode: dataVersion.value, parseDataCacheId: parseDataCacheId.value, fieldNum: res.data.fieldNum, fieldEntry: res.data.fieldEntry });
                upload.open = false;
              } else {
                newFileList.value = fileList.value;
                emit('sureUploadFile', { list: newFileList.value, tempVersionCode: dataVersion.value, parseDataCacheId: parseDataCacheId.value, fieldNum: res.data.fieldNum, fieldEntry: res.data.fieldEntry });
                upload.open = false;
              }
            })
            .catch(() => {
              parseDataCacheId.value = null;
              emit('cacheId', { parseDataCacheId: parseDataCacheId.value });
              newFileList.value = [];
              emit('sureUploadFile', { list: newFileList.value, tempVersionCode: dataVersion.value, parseDataCacheId: parseDataCacheId.value, fieldNum: null, fieldEntry: null });
              upload.open = false;
            })
        } else {
          dataList.value = res.data.list;
          titleList.value = res.data.name;
          title.value = res.data.typeName;
          dataVersion.value = res.data.dataVersion;
          show.value = res.data.show;
          if (res.data.open == '1') {
            openDrawer.value = true;
            newFileList.value = fileList.value;
            emit('sureUploadFile', { list: newFileList.value, tempVersionCode: dataVersion.value, parseDataCacheId: parseDataCacheId.value, fieldNum: res.data.fieldNum, fieldEntry: res.data.fieldEntry });
            upload.open = false;
          } else {
            newFileList.value = fileList.value;
            emit('sureUploadFile', { list: newFileList.value, tempVersionCode: dataVersion.value, parseDataCacheId: parseDataCacheId.value, fieldNum: res.data.fieldNum, fieldEntry: res.data.fieldEntry });
            upload.open = false;
          }
        }

      }).catch(err => {
        proxy.$modal.closeLoading();
      });
    } else {
      if(props.isTif){
        proxy.$modal.msgError(`必须上传.tif类型的文件！ `);
      }else{
        proxy.$modal.msgError(`必须上传.dbf、.prj、.shp、.shx、.cpg类型的文件！ `);
      }
    }
  } else {
    newFileList.value = [];
    let id = [];
    fileList.value.forEach(item => {
      id.push(item.attachId)
    })
    proxy.$modal.loading("正在解析文件，请稍候...");
    getListExcel({ typeCode: props.code, fileId: id.join(','), ...props.ids }).then(res => {
      proxy.$modal.closeLoading();
      console.log("getListExcel");
      console.log(res.data);
      if (res.data.code == 100001) {
        ElMessageBox.confirm(
          res.data.message,
          '消息',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
          }
        )
          .then(() => {
            parseDataCacheId.value = res.data.cacheId;
            emit('cacheId', { parseDataCacheId: parseDataCacheId.value });
            dataList.value = res.data.list;
            titleList.value = res.data.name;
            title.value = res.data.typeName;
            dataVersion.value = res.data.dataVersion;
            show.value = res.data.show;
            if (res.data.open == '1') {
              openDrawer.value = true;
              newFileList.value = fileList.value;
              emit('sureUploadFile', { list: newFileList.value, tempVersionCode: dataVersion.value, fieldNum: res.data.fieldNum, fieldEntry: res.data.fieldEntry });
              upload.open = false;
            } else {
              newFileList.value = fileList.value;
              emit('sureUploadFile', { list: newFileList.value, tempVersionCode: dataVersion.value, fieldNum: res.data.fieldNum, fieldEntry: res.data.fieldEntry });
              upload.open = false;
            }
          })
          .catch(() => {
            parseDataCacheId.value = null;
            emit('cacheId', { parseDataCacheId: parseDataCacheId.value });
            newFileList.value = [];
            emit('sureUploadFile', { list: newFileList.value, tempVersionCode: dataVersion.value, fieldNum: null, fieldEntry: null });
            upload.open = false;
          })
      } else {
        dataList.value = res.data.list;
        titleList.value = res.data.name;
        title.value = res.data.typeName;
        dataVersion.value = res.data.dataVersion;
        show.value = res.data.show;
        if (res.data.open == '1') {
          openDrawer.value = true;
          newFileList.value = fileList.value;
          emit('sureUploadFile', { list: newFileList.value, tempVersionCode: dataVersion.value, parseDataCacheId: parseDataCacheId.value, fieldNum: res.data.fieldNum, fieldEntry: res.data.fieldEntry });
          upload.open = false;
        } else {
          newFileList.value = fileList.value;
          emit('sureUploadFile', { list: newFileList.value, tempVersionCode: dataVersion.value, parseDataCacheId: parseDataCacheId.value, fieldNum: res.data.fieldNum, fieldEntry: res.data.fieldEntry });
          upload.open = false;
        }
      }

    }).catch(err => {
      proxy.$modal.closeLoading();
    });
  }



};

// 模板下载
function importTemplate(name) {
  proxy.download("/fxfzaqbz/data/downloadExcel", {
    fileName: name
  }, name);
};

function openUpload() {
  if (!props.code) {
    ElMessageBox.alert('请先选择子数据类别', '消息提示', {
      confirmButtonText: '确认',
      type: 'warning'
    })
  } else {
    uploadDisabled.value = true;
    fileList.value = [];
    upload.title = "上传";
    upload.open = true;
    //根据上传类型设置上传路径
    if(props.isSpatialData==0){
      uploadFileUrl.value = import.meta.env.VITE_APP_BASE_API + "/attachment/uploadExcelFile"
    }else{
      if(props.isTif){
        uploadFileUrl.value = import.meta.env.VITE_APP_BASE_API + "/attachment/uploadTifFile"
      }else{
        uploadFileUrl.value = import.meta.env.VITE_APP_BASE_API + "/attachment/uploadShpFile"
      }
    }
  }
}

// 上传前校检格式和大小
function handleBeforeUpload(file) {
  // 校检文件类型
  if (props.fileType.length) {
    let fileExtension = "";
    if (file.name.lastIndexOf(".") > -1) {
      fileExtension = file.name.slice(file.name.lastIndexOf(".") + 1);
    }
    const isTypeOk = props.fileType.some((type) => {
      if (fileExtension && fileExtension.indexOf(type) > -1) return true;
      return false;
    });
    if (!isTypeOk) {
      proxy.$modal.msgError(`文件格式不正确, 请上传${props.fileType.join("/")}格式文件!`);
      return false;
    }
  }

  // if (!props.fileType.length) {
  //   // 非第一次上传
  //   console.log(fileList.value, '校验数组');
  //   if (fileList.value.length) {
  //     var falg = fileList.value.some(item => {
  //       const name = item.name.slice(0, item.name.lastIndexOf("."));
  //       const fileName = file.name.slice(0, file.name.lastIndexOf("."));
  //       console.log(name, fileName, '名称对比');
  //       if (name != fileName) {
  //         const uploadName = fileList.value[0].name.slice(0, fileList.value[0].name.lastIndexOf("."));
  //         proxy.$modal.msgError(`文件名称不正确, 请上传名称为${uploadName}的文件!`);
  //         return true;
  //       }
  //     })
  //     if (falg) { return false; }
  //     var falg1 = fileList.value.some(item => {
  //       const typeName = item.name.slice(item.name.lastIndexOf(".") + 1);
  //       const typeFileName = file.name.slice(file.name.lastIndexOf(".") + 1)
  //       if ((typeName == 'shp' && typeFileName == typeName) || (typeName == 'dbf' && typeFileName == typeName) || (typeName == 'prj' && typeFileName == typeName) || (typeName == 'shx' && typeFileName == typeName) || (typeName == 'cpg' && typeFileName == typeName)) {
  //         proxy.$modal.msgError(`该类型文件只能上传一个!`);
  //         return true;
  //       }
  //     })
  //     if (falg1) { return false; }
  //   }
  // }

  if (!props.fileType.length) {
    // 非第一次上传
    if (fileList.value.length) {
      var falg = fileList.value.some(item => {
        const name = item.name.slice(0, item.name.lastIndexOf("."));
        const fileName = file.name.slice(0, file.name.lastIndexOf("."));
        if (name != fileName) {
          const uploadName = fileList.value[0].name.slice(0, fileList.value[0].name.lastIndexOf("."));
          proxy.$modal.msgError(`文件名称不正确, 请上传名称为${uploadName}的文件!`);
          return true;
        }
      })
      if (falg) { return false; }
      let shp = 0;
      let dbf = 0;
      let prj = 0;
      let shx = 0;
      let cpg = 0;
      var falg1 =fileList.value.some(item => {
        let typeName = item.name.slice(item.name.lastIndexOf(".") + 1);
        if(typeName == 'shp'){
          shp++;
          if(shp>1){
            proxy.$modal.msgError(`每个类型的文件（shp、dbf、prj、shx、cpg）只能上传一个!`);
            return true;
          }
        }
        if(typeName == 'dbf'){
          dbf++;
          if(dbf>1){
            proxy.$modal.msgError(`每个类型的文件（shp、dbf、prj、shx、cpg）只能上传一个!`);
            return true;
          }
        }
        if(typeName == 'prj'){
          prj++;
          if(prj>1){
            proxy.$modal.msgError(`每个类型的文件（shp、dbf、prj、shx、cpg）只能上传一个!`);
            return true;
          }
        }
        if(typeName == 'shx'){
          shx++;
          if(shx>1){
            proxy.$modal.msgError(`每个类型的文件（shp、dbf、prj、shx、cpg）只能上传一个!`);
            return true;
          }
        }
        if(typeName == 'cpg'){
          cpg++;
          if(cpg>1){
            proxy.$modal.msgError(`每个类型的文件（shp、dbf、prj、shx、cpg）只能上传一个!`);
            return true;
          }
        }
        // if ((typeName == 'shp' ) || (typeName == 'dbf') || (typeName == 'prj') || (typeName == 'shx') || (typeName == 'cpg')) {
        //   proxy.$modal.msgError(`每个类型的文件（shp、dbf、prj、shx、cpg）只能上传一个!`);
        //   return true;
        // }
      })
      if (falg1) { return false; }
    }
  }

  // 校检文件大小
  if (props.fileSize) {
    if (props.isSpatialData == '1') {
      var isLt = (file.size / 1024 / 1024 <= 1024);
      if (!isLt) {
        proxy.$modal.msgError(`上传文件大小不能超过1204MB!`);
        return false;
      }
    } else {
      var isLt1 = (file.size / 1024 / 1024 <= props.fileSize);
      if (!isLt1) {
        proxy.$modal.msgError(`上传文件大小不能超过 ${props.fileSize} MB!`);
        return false;
      }
    }
  }
  proxy.$modal.loading("正在上传文件，请稍候...");
  upload.isUploading = true;
  number.value++;
  return true;
}

function handleChange(file, fileList) {
  fileList.value = fileList;
}

// 文件个数超出
function handleExceed() {
  proxy.$modal.msgError(`上传文件数量不能超过 ${props.limit} 个!`);
}

// 上传失败
function handleUploadError(err) {
  proxy.$modal.closeLoading();
  proxy.$modal.msgError("上传文件失败");
}

// 上传成功回调
function handleUploadSuccess(res, file) {
  if (res.code == 200) {
    fileList.value.forEach(item=>{
      item.attachId =  item.response?.data[0].attachId,
      item.name = item.response?.data[0].attachName,
      item.url= item.response?.data[0].attachPath
    })
    // fileList.value.push({ attachId: res.data[0].attachId, name: res.data[0].attachName, url: res.data[0].attachPath });
    proxy.$modal.closeLoading();
    proxy.$modal.msgSuccess("上传文件成功");
    emit('uploadFile', fileList.value);
    let nameArr = [];
    fileList.value.forEach(item => {
      const typeName = item.name.slice(item.name.lastIndexOf(".") + 1);
      nameArr.push(typeName)
    })
    if (props.isTif==false && (nameArr.includes('shp' && 'dbf' && 'prj' && 'shx' && 'cpg')) && props.isSpatialData == '1') {
      console.log('上传文件可以解析');
      uploadDisabled.value = false;
    } else if (props.isTif && (nameArr.includes('tif')) && props.isSpatialData == '1') {
      console.log('上传文件可以解析');
      uploadDisabled.value = false;
    } else {
      uploadDisabled.value = true;
    }
  }else if(res.code == 500){
    proxy.$modal.closeLoading();
    proxy.$modal.msgError("上传文件失败");
    handleRemove()
  }
}

// 删除文件
function handleDelete(index, file) {
  // fileList.value.splice(index, 1);
  // emit('delFile', fileList.value);
  newFileList.value = [];
  emit('dels', [])
}

// 删除文件
function handleRemove (file, uploadFiles) {
  if(file&&file.response.code==200){
    const index = fileList.value.findIndex(item => item.attachId === file.response?.data[0].attachId)
    fileList.value.splice(index, 1)
  }else{
    fileList.value=fileList.value.filter(item => item.response.code == 200)
  }
}


// 下载文件
function handleDownload(file) {
  var query = {
    attachId: file.attachId,
    name: file.attachName
  }
  location.href = import.meta.env.VITE_APP_BASE_API + "/attachment/downLoadFile?attachId=" + encodeURIComponent(query.attachId);
}

function getFileName(name) {
  return name
}

defineExpose({
  fileList
});
</script>

<style scoped lang="scss">
.upload-file {
  width: 100%;
}

.upload-file-uploader {
  margin-bottom: 5px;
}

.upload-file-list .el-upload-list__item {
  border: 1px solid #e4e7ed;
  line-height: 2;
  margin-bottom: 10px;
  position: relative;
}

.upload-file-list .ele-upload-list__item-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  color: inherit;
}

.ele-upload-list__item-content-action .el-link {
  margin-right: 10px;
}

.el-upload-list__item-name {
  width: 310px !important;
  // white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

:deep(.el-upload-list__item){
  .el-upload-list__item-info{
    .el-upload-list__item-name{
      display: block;
      white-space: pre-wrap!important;
      overflow: hidden;
      // text-overflow: ellipsis;
      max-width: 340px; /* 根据需要调整宽度 */
      cursor: pointer;
      padding: 0 20px 0 4px!important;
    }
  }  
}
</style>
